import Taro from '@tarojs/taro';
import { requestUrl , baseUrl , baseImgSrc } from './base_url';
import { getGlobalData } from './globaldata';
import { getMyPending } from './api';
/**
 * @desc 单选函数
 * @param list 需要处理的数组
 * @param idx 需要处理的数组下标
*/
const singleCheck = (list = [],idx = 0) => {
    list = list.map(function(v,i){
        v.status = i == idx;
        return v
    })
    return list
 }
 /**
  * @desc 多选函数
  * @param list 需要处理的数组
  * @param idx  需要处理的下标
 */
 const multipleCheck = (list = [],idx = 0) => {
   list[idx].status = !list[idx].status;
   return list;
 }
/**
 * @desc 可取消的单选
*/ 
const singCheckCancle = (list = [],idx = 0) => list.map((v,i) => {v.status = i == idx ? !v.status :  v.status; return v})
//  登录
const toLogin = () => {
    Taro.navigateTo({
        url:"/pages/login/login"
    })
}
const axios = ({url,data = {},method = 'post',topLoading = false}) => {
    data.token = Taro.getStorageSync('userToken') || "";
    return new Promise((resolve,reject) => {
        topLoading ? Taro.showNavigationBarLoading() :  Taro.showLoading({title:"加载中"});
        Taro.request({
            url: requestUrl + url,
            header: {
                'content-type': 'application/json',
            },
            data,method,
            success(res){
                topLoading ? Taro.hideNavigationBarLoading() :  Taro.hideLoading();
                resolve(res.data)
            },
            fail(err){
                topLoading ? Taro.hideNavigationBarLoading() :  Taro.hideLoading();
                reject(err)
            }
        })
    })
}  
const upFile = ({urlPath,filePath,fileName}) => {
    return new Promise((resolve,reject) => {
        Taro.showLoading({title:"上传中"});
        Taro.uploadFile({
            url:requestUrl + urlPath,
            filePath:filePath,
            name:fileName,
            success(res){
                Taro.hideLoading()
                resolve(JSON.parse(res.data))
            },
            fail(err){
                Taro.hideLoading()
                Taro.showToast({title:"server500"+urlPath})
                reject(err)
            }
        })
    })
}
const getNowFormatDate = (day = 0) => {
    var day3 = new Date();
    day3.setTime(day3.getTime()+(day*24*60*60*1000));
    return day3.getFullYear()+'年'+(day3.getMonth()+1)+ "月" + day3.getDate() +'日';
}
function renderDateTree(){
    var myDate = new Date();
    var currentHouse =  myDate.getHours();
    var currentMinutes = myDate.getMinutes();
    var needCHouse = [];
    var needMin = [];
    for(let i = 0;i<=23;i++){
        if(currentHouse <=i){
            needCHouse.push(i+'点')
        }
    }
    for(let j = 0;j<=5;j++){
        if(Math.ceil(currentMinutes / 10)  <= j){
            needMin.push((j * 10)+'分')
        }
    }
    let monthList = [1+'点',2+'点',3+'点',4+'点',5+'点',6+'点',7+'点',8+'点',9+'点',10+'点',11+'点',12+'点',13+'点',14+'点',15+'点',16+'点',17+'点',18+'点',19+'点',20+'点',21+'点',22+'点',23+'点',24+'点']
    let minutes = [0,10+'分',20+'分',30+'分',40+'分',50+'分'];
    let list = [getNowFormatDate(0),getNowFormatDate(1),getNowFormatDate(2)];
    if(needMin.length == 0){
        needMin = JSON.parse(JSON.stringify(minutes));
    }
    if(needCHouse.length == 0 && needMin.length == 0){
        list.splice(0,1);
        needMin = JSON.parse(JSON.stringify(minutes));
        needCHouse = JSON.parse(JSON.stringify(monthList));
    }
    currentHouse+='点';
    currentMinutes+='分';
    //2020-4-17 新增逻辑整体时间后移1个小时
    // needMin = minutes;
    // needCHouse.splice(0,1) 2
    if(needMin.length <= 3 || needMin.length == 6 ){
        needMin = (JSON.parse(JSON.stringify(minutes))).splice(3 - needMin.length);
        needCHouse.splice(0,1)
        //处理当前时间
        currentHouse = needCHouse[0];
    }else{
        needMin.splice(0,3)
    } 
    return {
        dayList:list,
        houList:monthList,
        currentHou:currentHouse,
        currentMin:currentMinutes,
        currentDay:getNowFormatDate(0),
        hou:needCHouse,
        min:needMin,
        minList:minutes,
    }
}
//生成数据格式
function renderDate(){
    let allDate = renderDateTree();
    console.log(allDate)
     //处理日期
     let firstDate = allDate.min.map(v => {
        return {
            name:v,
        }
    });
    let secendDate = allDate.minList.map(v => {
        return {
            name:v
        }
    })
    //处理年
    let dateTree =  allDate.dayList.map((v,i) => {
        return {
            name:v,
            children:[],
        }
    });
    //处理日期
    dateTree = dateTree.map((v,i) => {
        if(i == 0){
            v.children = allDate.hou.map(v1 => {
                return {
                    name:v1,
                    children:secendDate
                }
            });
        }else{
            v.children = allDate.houList.map(v1 => {
                return {
                    name:v1,
                    children:secendDate
                }
            });
        }
        return v
    })
    dateTree[0].children[0].children = firstDate;
    return dateTree;
}
function handerTree(select){
    let aTree = renderDate();
    let arr1 = [],arr2 = [], arr3 = [];
    arr1 = aTree.map(v => v.name);
    arr2 = aTree[select[0]].children.map( v => v.name);
    arr3 = aTree[select[0]].children[select[1]].children.map( v => v.name);
    return [arr1,arr2,arr3]
}
const toWaitOrder = () => {
    getMyPending().then( res => {
        if(res.code == 0){ //存在正在进行中订单
            Taro.navigateTo({
                url:"/pages/receipt/receipt"
            })
        }else{

        }
    })
}
const intervalMin = (cTime,eTime) => {
    var diffValue = eTime - cTime;
    if(diffValue < 0){
        return 'end'
    }
    var m = Math.floor(diffValue / 60);
	var s = Math.floor(diffValue % 60);
	if (m < 10) {
		m = "0"+m
	}
	if (s < 10) {
		s = "0"+s
	}
	return{
		m:m,
		s:s,
	}
}
const navigateMap = (latitude,longitude,name = "",address = "") =>{ //调用微信内置地图导航
    latitude = Number(latitude);
    longitude = Number(longitude);
    wx.openLocation({ 
        latitude,//要去地点的纬度
        longitude,///要去地点的经度-地址
        name,
        address,
    })
}
const handerMainDate = (value) => {
    var myDate = new Date(value);
    return `${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()} ${myDate.getHours()}:${myDate.getMinutes()}`
}
const diffId = (arr1,arr2) => {
    var ids1 = arr1.map(v => v.id);
    var ids2 = arr2.map(v => v.id);
    let status = false;
    ids1.map(v => {if(ids2.indexOf(v) == -1){status = true;}})
    return {
        status:status,
        list:status ? arr1 : arr2,
    }
}
export {
    baseImgSrc,
    baseUrl,
    requestUrl,
    axios,
    upFile,
    singleCheck,
    multipleCheck,
    toLogin,
    getNowFormatDate,
    singCheckCancle,
    renderDateTree,
    toWaitOrder,
    intervalMin,
    navigateMap,
    handerMainDate,
    diffId,
    renderDate,
    handerTree,
}